<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    public $api_url ;
    public function __construct()
    {
        parent::__construct();
        header("Content-type:text/html;charset=utf-8;");

        $this->url = 'http://schoolgood.cn/Abutment/';
    }

    //我的缴费
    public function mypay(){
        //获取openid
        if(!$openid = I('get.openid')){

            $openid = $this->get_openid();
        }
        //echo $openid;exit;
        //获取所有订单
        $timestamp = time()*1000;
        $key = md5(strtolower($openid.$timestamp));
        $url = $this->url.'jxt_getorderlist';
        $data = array(
            'open_id' => $openid,
            'timestamp' => $timestamp,
            'key' => $key
        );
        $res = json_decode(https_curl($url,$data),true);
        //dump($res);exit;
        if($res['code'] == 1000 && $res['success']){
            $list = $res['data'];
        }else{
            echo '获取订单失败';
        }
        //dump($list);exit;

        $this->assign('list',$list);
        $this->display();
    }

    //我要缴费
    public function setpay(){
        //获取学校
        $timestamp = time()*1000;
        $key = md5($timestamp);
        $str = 'timestamp='.$timestamp.'&key='.$key;
        $url = $this->url.'jxt_getcompany';
        $data = array(
            'timestamp' => $timestamp,
            'key' => $key
        );
        $res = json_decode(https_curl($url,$data),true);
        //dump($res);exit;
        if($res['code'] == 1000 && $res['success']){
            $list = $res['data'];
        }else{
            echo '<h1>获取学校失败</h1>';
            exit;
        }

        //获取openid
        $openId = $this->get_openid();
        $this->openid = $openId;
        //dump($openId);exit;
        $this->assign('openid',$openId);
        $this->assign('school',$list);
        $this->display();

    }

    public function school_setpay(){
        $key = I('get.key');
        $arr = explode('&',$key);
        $fid = explode('=',$arr[1]);
        $fid = $fid[1];
        $fname = explode('=',$arr[2]);
        $fname = $fname[1];

        //根据学校获取班级
        $timestamp = time()*1000;
        $key = md5($fid.$timestamp);
        $url = $this->url.'jxt_getdeparement';
        $data = array(
            'company_id' => $fid,
            'timestamp' => $timestamp,
            'key' => $key
        );

        $res = json_decode(https_curl($url,$data),true);
        //dump($res);exit;
        if($res['code'] == 1000 && $res['success']){
            if(!$res['data']){
                echo '<h1>班级为空</h1>';
                exit;
            }
            $list = $res['data'];
        }else{
            echo '<h1>获取班级失败</h1>';
            exit;
        }
        //dump($list);exit;
        //获取openid
        $openId = $this->get_openid();

        $this->assign('openid',$openId);
        $this->assign('banji',$list);
        $this->assign('fid',$fid);
        $this->assign('fname',$fname);
        $this->display();
    }

    /**获取接口数据
     * @param $url  接口地址
     * @param $str  参数
     * @return bool|mixed|string
     */
    private  function get_api_result($url,$str){
        $url = $url .'?'.$str;
       // echo $url;
        $res = file_get_contents($url);
        $res = json_decode($res,true);
        return $res;
    }


    /**
     * ajax获取班级
     */
    public function get_banji(){
        $fid = I('get.fid');
        //$fid = '077f3a55-278e-40f9-b822-52897fdbb758';

        $timestamp = time()*1000;
        $key = md5($fid.$timestamp);
        $url = $this->url.'jxt_getdeparement';
        $data = array(
            'company_id' => $fid,
            'timestamp' => $timestamp,
            'key' => $key
        );

        $res = json_decode(https_curl($url,$data),true);
        //dump($res);exit;
        if($res['code'] == 1000 && $res['success']){
            $code = 0;
            $msg = '';
            if(!$res['data']){
                $code = 2;
                $msg = '班级为空';
            }
            $list = $res['data'];
        }else{
            $code = 1;
            $msg = '获取班级失败';
            $list = '';
        }
        //dump($list);exit;
        $arr = array(
            'code' => $code,
            'msg' => $msg,
            'list' => $list
        );

        $this->ajaxReturn($arr);

    }

    //确认缴费
    public function qrpay(){
        $data = I('post.');
        //dump($data);exit;
        //计算金额
        if($data['radio_money'] == 1){
            $data['money'] = $data['zdy_money']*100;
        }else{
            $data['money'] = $data['radio_money']*100;
        }

        //测试金额
        //$data['money'] = 1;
        $order_id = date('YmdHis').rand(1000,9999);
        $time = time()*1000;
        $key = md5($order_id.$time);

        //分解学校和班级
        $school = explode('__',$data['school']);
        $class = explode('__',$data['class']);
        //生成订单
        $order = array(
            'order_id'  => $order_id,
            'open_id'   => $data['openid'],
            'money'     => $data['money'],
            'order_time'=> time(),
            'pay_time'  => 0,
            'company_id'=> $school[0],
            'department_id'=> $class[0],
            'student'   => $data['student'],
            'phone'     => $data['phone'],
            'type'      => 1,
            'timestamp' => $time,
            'key'       =>$key
        );

        $url = $this->url.'jxt_setorder';
        $res = json_decode(https_curl($url,$order),true);
        //dump($res);exit;
        if($res['code'] == 1000 && $res['success']){
            //dump($order);exit;
            //②、统一下单
            $jsApiParameters = $this->set_order($order);

            //保存数据
            $orders[$order['order_id']] = $order;
            //dump($orders);exit;
            S('order',serialize($orders));

            //dump($jsApiParameters);
            //dump($order);exit;
            $this->assign('jsApiParameters',$jsApiParameters);
            $this->assign('order',$order);
            $this->assign('school',$school[1]);
            $this->assign('class',$class[1]);
            $this->display();
        }else{
            echo $res['msg'];
            exit;
        }

    }

    public function aa(){
        $orderid = 201803051758418998;
        $timestamp = time()*1000;
        $key = md5($orderid.$timestamp);
        $time = time();
        $url = 'http://schoolgood.cn/Abutment/jxt_updateorder';
        $data = array(
            'timestamp' => $timestamp,
            'order_id' => $orderid,
            'time' => $time,
            'type' => 2,
            'key' => $key
        );
        $res = json_decode(https_curl($url,$data),true);
        dump($res);
    }

    /**获取openid
     * @return 用户的openid
     */
    private function get_openid(){
        require_once "./Org/wxpay/example/WxPay.JsApiPay.php";
        //获取openid
        $tools = new \JsApiPay();
        $openId = $tools->GetOpenid();
        //dump($openId);exit;
        return $openId;
    }

    /**统一下单
     * @param $orderinfo
     * @return \json数据，可直接填入js函数作为参数
     */
    private function set_order($orderinfo){
        require_once "./Org/wxpay/lib/WxPay.Api.php";
        require_once "./Org/wxpay/example/WxPay.JsApiPay.php";
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("安全园务接送平台-缴费");
        //$input->SetAttach("test");
        $input->SetOut_trade_no($orderinfo['order_id']);
        $input->SetTotal_fee($orderinfo['money']);
        //$input->SetTime_start(date("YmdHis"));
        //$input->SetTime_expire(date("YmdHis", time() + 600));
        //$input->SetGoods_tag("test");
        $input->SetAppid(C('appid'));//公众账号ID
        $input->SetMch_id(C('mchid'));//商户号
        $input->SetNotify_url("http://jxt.anan365.com/jiaofei/index.php/Home/Notice/wxpay_notify");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($orderinfo['open_id']);
        $order = \WxPayApi::unifiedOrder($input);
        //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
        //dump($order);exit;
        $tools = new \JsApiPay();
        $jsApiParameters = $tools->GetJsApiParameters($order);
        //dump($jsApiParameters);exit;
        return $jsApiParameters;
    }

    /**
     * 查询微信订单支付状态
     */
    public function seach_wxorder(){
        $this->redirect('mypay');
        exit;

        $orderid = I('get.orderid');
        //$orderid = '201804041805199204';
        require_once "./Org/wxpay/lib/WxPay.Api.php";
        sleep(1);

        $input = new \WxPayOrderQuery();
        $input->SetOut_trade_no($orderid);
        $input->SetAppid(C('appid'));
        $input->SetMch_id(C('mchid'));

        $payapi = new \WxPayApi();
        $result = $payapi->orderQuery($input);
        if($result['return_code']=='SUCCESS' && $result['result_code']=='SUCCESS'){
            $this->redirect('mypay');
        }else{
            $this->error('支付失败');
        }


    }

    //扫一扫
    public function scan_code(){

        $tick = $this->get_jsapi_ticket();
        $str = $this->get_str();
        $url = 'http://jxt.anan365.com/jiaofei/index.php/Home/Index/scan_code';
        $time = time();
        $sign = $this->get_sign($tick,$url,$str,$time);
        //$this->jssdk('wxe17c19bfa5f3f56e','0ea6aba5a7d914a4f56f17e5b06cea8d');
        $this->assign(array(
            'sign' => $sign,
            'str'  => $str,
            'time' => $time
        ));
        $this->display();
    }




    /**获取签名
     * @param $ticket
     * @param $url
     * @param $nostr
     * @param $timestamp
     * @return string
     */
    private function get_sign($ticket,$url,$nostr,$timestamp){

        $arr = array(
            'noncestr' => $nostr,
            'jsapi_ticket' => $ticket,
            'timestamp' => $timestamp,
            'url' => $url
        );
        ksort($arr);
        $a = array();
        foreach ($arr as $key => $value) {
            $a[] = $key . '=' . $value;
        }
        $sign = sha1(implode("&", $a));
        return $sign;
    }



    /**获取jsapi_ticket
     * @param $access_token
     * @return mixed
     */
    protected function get_jsapi_ticket(){
        if($ticket = S('jsapi_ticket')){
            $ticket = unserialize($ticket);
        }else{
            //获取access_token
            $token = $this->get_access_token();
            $url= "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$token&type=jsapi";
            $res = json_decode(file_get_contents($url),true);
            $ticket = $res['ticket'];

            S('jsapi_ticket',serialize($ticket),7100);
        }
        return $ticket;
    }

    /**获取access_token
     * @return mixed
     */
    private function get_access_token(){
        if($token = S('access_token')){
            $token = unserialize($token);
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxe17c19bfa5f3f56e&secret=0ea6aba5a7d914a4f56f17e5b06cea8d";
            $res1 = json_decode(file_get_contents($url),true);
            $token = $res1['access_token'];

            S('access_token',serialize($token),7100);
        }
        return $token;
    }

    protected function get_str(){
        $str = 'abcdefghijglmnopqrstuvwsyzABCDEFGHIJKLMNOPQRSTUVWSYZ123456789';
        $str = substr(str_shuffle($str),0,8);
        return $str;
    }
}
